package httpHandler

import (
	baseHttp "gitee.com/zaiqiang231/go-base-app/base_app/http"
	"gitee.com/zaiqiang231/go-base-session/app/config"
	"gitee.com/zaiqiang231/go-base-session/app/model"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"net/http"
)

func CreateToken(context *gin.Context) {
	var request model.TokenCreateRequest
	if err := context.ShouldBindBodyWith(&request, binding.JSON); err != nil {
		baseHttp.WriteResponse(context, http.StatusBadRequest, err.Error(), nil)
		return
	}
	token, err := config.GlobalJwtAuth.CreateToken(request.IdentityKey, request.Timeout)
	if err != nil {
		baseHttp.WriteResponse(context, http.StatusInternalServerError, err.Error(), nil)
		return
	}
	baseHttp.WriteResponse(context, 0, "success", gin.H{
		"token": token,
	})
}

func CheckToken(context *gin.Context) {
	var request model.TokenCheckRequest
	if err := context.ShouldBindBodyWith(&request, binding.JSON); err != nil {
		baseHttp.WriteResponse(context, http.StatusBadRequest, err.Error(), nil)
		return
	}
	isValid, identity, err := config.GlobalJwtAuth.TokenCheck(request.Token)
	if err != nil {
		baseHttp.WriteResponse(context, http.StatusInternalServerError, err.Error(), nil)
		return
	}
	baseHttp.WriteResponse(context, 0, "success", gin.H{
		"isValid":  isValid,
		"identity": identity,
	})
}
